<template>
    <div class="page-profile profile">
        <div class="loading" v-show="loading">
            <div class="loading-inside">
                <van-loading type="spinner" />
            </div>
        </div>
        <div class="user-info-box">
        <van-nav-bar left-arrow @click-left="$router.back(-1)" :title="$t('m.Profile')" style="color:#fff;">
        </van-nav-bar>
            <input type="file" accept="image/*" name="photos"  @change="getFile" style="display: none;">
        <van-cell-group>
            <van-cell :title="$t('m.Photo')" is-link class="head-image" @click='addPic'>
                <img :src="headerImage" :onerror="defaultHeadImg" class="image-icon"/>
            </van-cell>
            <van-cell :title="$t('m.Description')" is-link :value="translateString(description)" class="description-cell" @click="goToDev(description)"/>
            <van-cell :title="$t('m.UserName')" is-link :value="translateString(username)" @click="namePop = true"/>
            <van-cell :title="$t('m.Gender')" is-link :value="getGender(genderId)" @click="genderPop = true" />
            <van-cell :title="$t('m.Birthdate')" is-link :value="getBirthDate(birthDate)" @click="birthDatePop = true" />
        </van-cell-group>
        <van-cell-group style="border-top:10px solid #F2F2F2;">
            <van-cell :title="$t('m.Phone')" is-link :value="phone" @click="smsPhone" />
            <van-cell :title="$t('m.Displayphonetobuyer')" clickable @click="toggleChange" v-if="phone">
                <van-checkbox v-model="displayPhone" ref="displayPhone" @change="changeDisplay()"/>
            </van-cell>
            <!--<van-cell title="Email" is-link :value="getEmail(userEmail)" @click="emailPop = true" />-->
            <van-cell title="Facebook" :label="facebook" class="facebook-bind" v-if="facebook">
                <span @click="deleteBindFacebook">{{$t('m.Unlink')}}</span>
            </van-cell>
            <van-cell title="Facebook" class="facebook-bind" v-else>
                <span @click="faceBookLogin">{{$t('m.Link')}}</span>
            </van-cell>
            <van-cell :title="$t('m.Password')" is-link @click="goToPass()"/>
        </van-cell-group>
        </div>
        <div class="filter-btn">
            <van-button type="default"  size="large" class="logout-btn" @click="Logout">{{$t('m.Logout')}}</van-button>
        </div>

        <!--头像弹窗-->
        <div id="demo" v-show="panel">
            <!-- 遮罩层 -->
            <div class="container">
                <div>
                    <img id="image" :src="url" alt="Picture">
                </div>

                <button type="button" id="button" @click="crop">{{$t('m.Save')}}</button>
                <button type="button" id="cancel" @click="cancelCrop">{{$t('m.Cancel')}}</button>
            </div>
        </div>
        <!--名称弹窗-->
        <van-dialog
            v-model="namePop"
            show-cancel-button
            :close-on-click-overlay="true"
            confirm-button-text="Save"
            :before-close="nameBeforeClose"
            style="width:80%;">
            <div class="login-box-inside">
                <div class="email-box">
                    <label for="userName" class="label-class">{{$t('m.UserName')}}</label>
                    <input type="text" v-model="nameSubmit" @input="setNameError()" id="userName" v-bind:class="{'text-danger': nameError }" class="input-class email-input" />
                    <span v-show="nameError" style="color: #fa5555;">
                        <span v-if="nameAlreadyExists">{{$t('m.Usernamealreadyexists')}}</span>
                        <span v-else>{{$t('m.InvalidName')}}</span>
                    </span>
                    <p>{{$t('m.Letternumberunderscoreperiodsonly')}}</p>
                    <p>{{$t('m.Nomorethanoneunderscore')}}</p>
                    <p>{{$t('m.Letternumbercharacters')}}</p>
                </div>
            </div>
        </van-dialog>
        <!--性别弹窗-->
        <van-popup v-model="genderPop" style="width:80%;">
            <van-radio-group v-model="gender">
                <van-cell-group>
                    <van-cell :title="item.text" clickable :key="index" @click="changeGender(item.value)" v-for="(item, index) in genderArr">
                        <van-radio :name="item.value" />
                    </van-cell>
                </van-cell-group>
            </van-radio-group>
        </van-popup>
        <!--生日弹窗-->
        <van-popup v-model="birthDatePop" style="width:80%;">
            <van-datetime-picker
                v-model="currentDate"
                type="date"
                :min-date="minDate"
                @confirm = "changeBirthdate"
                @cancel = "cancelBirthdate"
            />
        </van-popup>
        <!--电话弹窗-->
        <!--<van-dialog
            v-model="phonePop"
            show-cancel-button
            :close-on-click-overlay="true"
            confirm-button-text="Save"
            :before-close="phoneBeforeClose"
            style="width:80%;">
            <div class="login-box-inside">
                <div class="email-box">
                    <label for="phoneNumber" class="label-class">{{$t('m.Phone')}}</label>
                    <div class="phone-box">
                        <input type="text" v-model="phoneSubmit" @input="setPhoneError()" id="phoneNumber" v-bind:class="{'text-danger': phoneError }" class="input-class email-input" />
                    </div>
                    <span v-if="phoneError" style="color: #fa5555;">Invalid phone</span>
                </div>
            </div>
        </van-dialog>-->
        <!--邮箱弹窗-->
        <!--<van-popup v-model="emailPop" class="email-login-box" style="width:80%;">
            <div v-if="!userEmail">
                <div class="email-box-title">Add Email</div>
                <div class="email-box">
                    <label for="email" class="label-class">{{$t('m.Email')}}</label>
                    <input type="text" v-model="email" @input="setEmailError()" id="email" v-bind:class="{'text-danger': emailError }" class="input-class email-input" />
                    <span v-if="emailError" style="color: #fa5555;">Invalid email</span>
                </div>
                <div class="password-box">
                    <label for="password" class="label-class">{{$t('m.Password')}}</label>
                    <div class="password-inside-box">
                        <input type="password" v-model="password" @input="setPasswordError" id="password" v-bind:class="{'text-danger': passwordError }" class="input-class password-input" />
                    </div>
                    <span v-if="passwordError" style="color: #fa5555;">At least 8 or more characters.</span>
                </div>
                <div class="login-btn">
                    <van-button size="large" class="btn" @click="changeEmail" :disabled="loadingEmail"><van-loading class="login-loading" type="spinner" color="white"  v-if="loadingEmail"/>Send validation to my email</van-button>
                </div>
            </div>
            <div v-else>
                <div class="email-box-title">Change Email</div>
                <div class="password-box">
                    <label for="password1" class="label-class">{{$t('m.Password')}}</label>
                    <div class="password-inside-box">
                        <input type="password" v-model="password" @input="setPasswordError" id="password1" v-bind:class="{'text-danger': passwordError }" class="input-class password-input" />
                    </div>
                    <span v-if="passwordError" style="color: #fa5555;">At least 8 or more characters.</span>
                </div>
                <div class="email-box">
                    <label for="email1" class="label-class">New email</label>
                    <input type="text" v-model="email" @input="setEmailError()" id="email1" v-bind:class="{'text-danger': emailError }" class="input-class email-input" />
                    <span v-if="emailError" style="color: #fa5555;">Invalid email</span>
                </div>
                <div class="login-btn">
                    <van-button size="large" class="btn" @click="changeEmail" :disabled="loadingEmail"><van-loading class="login-loading" type="spinner" color="white"  v-if="loadingEmail"/>Send validation to my email</van-button>
                </div>
            </div>
        </van-popup>-->
    </div>
</template>
<script>
    import Cropper from 'cropperjs'
    import {setUserInfo, getUserInfo, uploadHeadImgAjax, bindingFacebook, unBindingFacebook, signOutUser} from '../../static/api/mgc_api'
    import Qs from 'qs';
    import {chatAppkey} from '../../static/api/zxy_api';

    export default {
        name: 'Profile',
        middleware: ['login'],
        data() {
            return {
                // activeNames: ['1'],
                defaultHeadImg: 'this.src="' + require('../../static/img/images/user-head.png') + '"',
                loading: false,
                screenHeight: document.body.clientHeight, // 这里是给到了一个默认值 （这个很重要），
                originHeight: document.body.clientHeight, //默认高度在watch里拿来做比较
                namePop: false,
                genderPop: false,
                birthDatePop: false,
                nameError: false,
                nameAlreadyExists: false,
                phonePop: false,
                emailPop: false,
                username: '', // 显示字段
                description: '',
                nameSubmit: '', // 提交字段
                gender: '',// 提交字段
                genderId: '',// 显示字段
                birthDate: null, // 提交字段
                currentDate: new Date(),
                minDate: new Date(1930, 0, 1),
                phoneError: false,
                phone: '', // 显示字段
                phoneSubmit: '', // 提交字段
                displayPhone: false, // 提交字段  DISPLAY((byte) 0),NOTDISPLAY((byte) 1)
                emailError: false,
                passwordError: false,
                email: '',// 提交字段
                userEmail: '', // 显示字段 // 用于判定是否有邮箱
                password: '', // 提交字段
                loadingEmail: false,
                facebook: '',
                isOriginHei: true,

                //图片裁剪
                headerImage:'',
                picValue:'',
                cropper:'',
                croppable:false,
                panel:false,
                url:''
            };
        },
        computed: {
            genderArr() {
                if (this.$store.state.store.localLang == 'MM') {
                    return [
                        {value: 0, text: 'အမ်ိဳးသား'},
                        {value: 1, text: 'အမ်ိဳးသမီး'},
                    ]
                } else if (this.$store.state.store.localLang == 'MMU') {
                    return [
                        {value: 0, text: 'အမျိုးသား'},
                        {value: 1, text: 'အမျိုးသမီး'},
                    ]
                } else {
                    return [
                        {value: 0, text: 'Male'},
                        {value: 1, text: 'Female'},
                    ]
                }
            },
        },
        methods: {
            initInfo () {
                this.loading = true
                getUserInfo().then((res) => {
                    if (res.data) {
                        if (res.data.errorID === 0) {
                            let userInfo = res.data.object
                            this.initInfoData(userInfo)
                            this.setNewLocalUserInfo(userInfo)
                            this.loading = false
                        } else if (res.data.errorID === 100004) {
                            this.$router.push('/login-register/loginregister')
                        } else {
                            this.$toast(res.data.message)
                            this.loading = false
                        }
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        this.$toast('error,please try again leter')
                        this.loading = false
                    })
            },
            translateString(str) {
                if (!str) return ''
                return this.$translateLang(str, 'unicodeTozawgyi');
            },
            initInfoData (userInfo) {
                if (!userInfo) return false;
                this.headerImage = userInfo.photo
                // 后台只存 Unicode, 前端只需在 zawgyi 环境下将 unicode 转成 zawgyi
                this.description = userInfo.description || ''
                this.username = userInfo.name || ''
                this.gender = userInfo.gender
                this.genderId = userInfo.gender
                if (userInfo.birthday) {
                    this.birthDate = new Date(userInfo.birthday)
                    this.currentDate = new Date(userInfo.birthday)
                }
                this.phone = userInfo.account || ''
                // DISPLAY((byte) 0),NOTDISPLAY((byte) 1)
                if (userInfo.displayPhone == 1) {
                    this.displayPhone = false
                } else {
                    this.displayPhone = true
                }

                // this.userEmail = userInfo.email || ''
                this.facebook = userInfo.facebookName || ''

            },
            // 修改本地缓存信息
            editLocalUserInfo(nameProperty, value) {
                let userInfo = localStorage.getItem("userInfo") || '';
                // 修改description后这里需要优化
                if (userInfo) {
                    userInfo = JSON.parse(userInfo);
                    userInfo[nameProperty] = value;
                    this.setNewLocalUserInfo(userInfo);
                }
            },
            // 保存用户信息
            setNewLocalUserInfo (i) {
                let _userInfo = JSON.stringify(i)
                localStorage.setItem("userInfo", _userInfo);
            },
            //修改头像 function
            initCropper() {
                var image = document.getElementById('image');
                this.cropper = new Cropper(image, {
                    aspectRatio: 1,
                    viewMode: 1,
                    background:false,
                    zoomable:false,
                    ready: () => {
                        this.croppable = true;
                    }
                });
            },
            addPic () {
                document.getElementsByName('photos')[0].click();
                return false;
            },
            cancelCrop () {
                this.panel = false;
                this.cropper.reset();
                document.getElementsByName('photos')[0].value = ''
            },
            getObjectURL (file) {
                var url = null ;
                if (window.createObjectURL!=undefined) { // basic
                    url = window.createObjectURL(file) ;
                } else if (window.URL!=undefined) { // mozilla(firefox)
                    url = window.URL.createObjectURL(file) ;
                } else if (window.webkitURL!=undefined) { // webkit or chrome
                    url = window.webkitURL.createObjectURL(file) ;
                }
                return url ;
            },
            getFile (e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length) return;
                this.panel = true;
                this.picValue = files[0];

                this.url = this.getObjectURL(this.picValue);
                //每次替换图片要重新得到新的url
                if(this.cropper){
                    this.cropper.replace(this.url);
                }
                this.panel = true;
            },
            crop () {
                // this.panel = false;
                var croppedCanvas;
                var roundedCanvas;

                if (!this.croppable) {
                    return;
                }
                // Crop
                croppedCanvas = this.cropper.getCroppedCanvas();
                // Round
                roundedCanvas = this.getRoundedCanvas(croppedCanvas);

                // this.headerImage = roundedCanvas.toDataURL();
                // canvas转为blob并上传
                roundedCanvas.toBlob((blob) => {
                    // console.log(blob)
                    // this.headerImage = URL.createObjectURL(blob)
                    this.postImg(blob)
                }, 'image/png', 0.95)
            },
            getRoundedCanvas (sourceCanvas) {

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                var width = sourceCanvas.width;
                var height = sourceCanvas.height;
                //为了每张图片的大小不超过50k,所以不论裁剪多大，最后上传的，最大宽度不超过90。
                if(width > 160){
                    width = 160
                }
                if(height > 160){
                    height = 160
                }
                canvas.width = width;
                canvas.height = height;

                context.imageSmoothingEnabled = true;
                context.drawImage(sourceCanvas, 0, 0, width, height);
                context.globalCompositeOperation = 'destination-in';
                context.beginPath();
                context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
                context.fill();

                return canvas;
            },
            postImg (blob) {
                //这边写图片的上传
                // document.getElementsByName('photos')[0].value = ''
                this.cancelCrop();
                let formData = new FormData()
                formData.append('file', blob)
                let config = {
                    'Content-Type': 'multipart/form-data'
                }
                this.loading = true
                uploadHeadImgAjax(formData, config).then((res) => {
                    if (res.data) {
                        if (res.data.errorID === 0) {
                            this.headerImage = res.data.object;
                            this.editLocalUserInfo('photo', res.data.object);
                            this.loading = false
                        } else if (res.data.errorID === 100004) {
                            this.$router.push('/login-register/loginregister')
                        } else {
                            this.$toast(res.data.message)
                            this.loading = false
                        }
                    }
                }).catch((error) => {
                    this.$toast('error, please try again later')
                    this.loading = false
                })
            },
            // 去修改description---
            goToDev(d) {
                this.$router.push({
                    name:'userDescrption',
                    params:{
                        dev: d
                    }
                })
            },
            //
            goToPass(){
                this.$router.push({
                    path:'/user/password',
                })
            },
            // 修改名称
            setNameError () {
                let nameSubmit = this.$translateLang(this.nameSubmit,'zawgyiTounicode')
                // let reg = /^[0-9A-Za-z_\u1000-\u109F]{1,20}$/
                // if (nameSubmit.match(reg)) {
                //     this.nameError = false
                // } else {
                //     this.nameError = true
                // }
                this.nameAlreadyExists = false
                if (5 <= nameSubmit.length <= 20) {
                    this.nameError = false
                } else {
                    this.nameError = true
                }
            },
            nameBeforeClose (action, done) {
                if (action === 'confirm') {
                    let chatNameZawgyi = this.nameSubmit || '';
                    //校验表单开始
                    let nameSubmit = this.$translateLang(this.nameSubmit,'zawgyiTounicode')
                    // let regName = /^[0-9A-Za-z_\u1000-\u109F]{1,20}$/
                    // if (!nameSubmit || !nameSubmit.match(regName)) {
                    //     this.nameError = true;
                    //     done(false);
                    //     return false
                    // }
                    if (nameSubmit.length < 5 || nameSubmit.length > 20) {
                        this.nameError = true;
                        done(false);
                        return false
                    }
                    //校验表单结束
                    let data = {
                        'name': nameSubmit,
                    }
                    let params = Qs.stringify(data)
                    setUserInfo(params).then((res) => {
                        if (res.data) {
                            if (res.data.errorID === 0) {
                                this.username = nameSubmit;
                                this.editLocalUserInfo('name', nameSubmit);
                                done();

                                // 尝试修改聊天部分的用户名，直接传zawgyi
                                if(window.applozic){
                                    $.ajax({
                                        url: "https://apps.applozic.com/rest/ws/user/update",
                                        type: 'POST',
                                        dataType: 'json',
                                        data: JSON.stringify({displayName: chatNameZawgyi}),
                                        beforeSend: function (xhr) {
                                            xhr.setRequestHeader("Application-Key", `${chatAppkey}`);
                                            xhr.setRequestHeader("Authorization", localStorage.getItem('Authorization'));
                                            xhr.setRequestHeader("Device-Key", localStorage.getItem('Device-Key'));
                                        },
                                        contentType: 'application/json',
                                        success: (res) => {
                                            if (res.status == 'success') {
                                                console.log(res,'修改聊天端用户名成功')
                                            }
                                        }
                                    });
                                }

                            } else if (res.data.errorID === 100000) {
                                this.nameAlreadyExists = true;
                                done(false);
                                return false
                            } else {
                                this.$toast(res.data.message)
                                done();
                            }
                        }
                    })
                        .catch((error) => {
                            console.log(error)
                            this.$toast('error,please try again leter')
                            done();
                        })
                } else {
                    done();
                }
            },
            //修改性别 function
            getGender(t) {
                let str = '';
                if (t !== '') {
                    this.genderArr.forEach((item) => {
                        if (item.value == t) {
                            str = item.text || ''
                        }
                    })
                }
                return str
            },
            changeGender(val) {
                let data = {
                    'gender': val,
                    'name':this.username
                };
                let params = Qs.stringify(data);
                setUserInfo(params).then((res) => {
                    if (res.data) {
                        if (res.data.errorID === 0) {
                            this.gender = val;
                            this.genderId = val;
                            this.editLocalUserInfo('gender', val);
                            this.genderPop = false
                        } else {
                            this.$toast(res.data.message);
                            this.gender = this.genderId;
                            this.genderPop = false
                        }
                    }
                })
                    .catch((error) => {
                        console.log(error);
                        this.$toast('error,please try again leter');
                        this.gender = this.genderId;
                        this.genderPop = false
                    })
            },

            //修改生日 function
            getBirthDate (value,type) {
                let t = type || ''
                if(!value){
                    return ''
                }
                var date = new Date(value)

                var Y = date.getFullYear()
                var m = date.getMonth() + 1
                var d = date.getDate()
                var H = date.getHours()
                var i = date.getMinutes()
                var s = date.getSeconds()
                if (m < 10) {
                    m = '0' + m
                }
                if (d < 10) {
                    d = '0' + d
                }
                if (H < 10) {
                    H = '0' + H
                }
                if (i < 10) {
                    i = '0' + i
                }
                if (s < 10) {
                    s = '0' + s
                }
                if (type) {
                    var ts = Y + '-' + m + '-' + d
                } else {
                    var ts = d + '-' + m + '-' + Y
                    // var ts = value
                }
                return ts
            },
            changeBirthdate(value) {
                let v = this.getBirthDate(value, 1)
                let data = {
                    'birthday': v,
                    'name':this.username
                }
                let params = Qs.stringify(data)
                setUserInfo(params).then((res) => {
                    if (res.data) {
                        if (res.data.errorID === 0) {
                            this.birthDate = value

                            let birthday = new Date(Date.parse(v.replace(/-/g,  "/"))).getTime();
                            this.editLocalUserInfo('birthday', birthday);
                            this.birthDatePop = false
                        } else {
                            this.$toast(res.data.message)
                            this.birthDatePop = false
                        }
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        this.$toast('error,please try again leter')
                        this.birthDatePop = false
                    })
            },
            cancelBirthdate () {
                this.birthDatePop = false
            },

            //修改手机 function
            getPhone(phone) {
                let p = '';
                if (phone && String(phone).length > 0) {
                    let t = phone.toString() || '';
                    let c = t.substring(t.length-2, t.length);
                    let _s = '';
                    for (var i = 0; i < t.length - 2; i++) {
                        _s += '*';
                    }
                    p = _s + c
                }
                return p;
            },
            toggleChange(){
                this.$refs.displayPhone.toggle();
            },
            changeDisplay() {
                // DISPLAY((byte) 0),NOTDISPLAY((byte) 1)
                // 选中的时候(this.displayPhone == true)传 0，非选中时传1
                let displayPhone = 0
                if (!this.displayPhone) {
                    displayPhone = 1
                }
                let data = {
                    'displayPhone': displayPhone,
                    'name':this.username
                }
                let params = Qs.stringify(data)
                setUserInfo(params).then((res) => {
                    if (res.data) {
                        if (res.data.errorID === 0) {
                            this.editLocalUserInfo('displayPhone', displayPhone);
                        } else {
                            this.$toast(res.data.message);
                            this.initInfoData(userInfo)
                        }
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        this.$toast('error,please try again leter')
                    })
            },
            //新增 facebook SMS start
            // initAccountKit () {
            //     const tag = document.createElement('script')
            //     tag.setAttribute(
            //         'src',
            //         `https://sdk.accountkit.com/en_US/sdk.js`
            //     )
            //     tag.setAttribute('id', 'account-kit')
            //     tag.setAttribute('type', 'text/javascript')
            //     tag.onload = () => {
            //         /* eslint-disable camelcase */
            //         window.AccountKit_OnInteractive = this.onLoad.bind(this)
            //         /* eslint-enable camelcase */
            //     }
            //     document.head.appendChild(tag)
            // },
            // onLoad () {
            //     window.AccountKit.init(
            //         {
            //             appId: "145205116120223",
            //             state: '1212111',
            //             version: "v1.1",
            //             display: "modal",
            //             fbAppEventsEnabled: true,
            //         }
            //     )
            // },
            // // login callback
            // loginCallback(response) {
            //     if (response.status === "PARTIALLY_AUTHENTICATED") {
            //         var code = response.code;
            //         // var csrf = response.state;
            //         // Send code to server to exchange for access token
            //         let data = {
            //             'phone': code,
            //             // 'csrf': csrf
            //         }
            //         let params = Qs.stringify(data)
            //         setUserInfo(params).then((res) => {
            //             if (res.data) {
            //                 var data = res.data
            //                 // let mes = JSON.parse(res.data.message)
            //                 if (data.errorID === 0) {
            //                     // this.$toast('register success')
            //                 } else {
            //                     this.$toast(data.message)
            //                 }
            //             }
            //         }).catch((error) => {
            //             console.log(error)
            //             this.$toast('error,please try again later')
            //         })
            //     }
            //     else if (response.status === "NOT_AUTHENTICATED") {
            //         console.log('Not Authenticated')
            //     }
            //     else if (response.status === "BAD_PARAMS") {
            //         this.$toast('Bad Params')
            //     }
            // },

            // phone form submission handler
            smsPhone() {
                // window.AccountKit.login('PHONE', {}, this.loginCallback)
                this.$router.push({
                    name:'userPhone',
                    params:{
                        phone: this.phone
                    }
                })
            },
            //新增 facebook SMS end

            // setPhoneError () {
            //     let reg = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/
            //     if (this.phoneSubmit.match(reg)) {
            //         this.phoneError = false
            //     }
            // },
            // phoneBeforeClose(action, done) {
            //     if (action === 'confirm') {
            //         //校验表单开始
            //         let regPhone = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/
            //         if (!this.phoneSubmit || !this.phoneSubmit.match(regPhone)) {
            //             this.phoneError = true;
            //             done(false);
            //             return false
            //         }
            //         //校验表单结束
            //         let data = {
            //             'phone': this.phoneSubmit,
            //         }
            //         let params = Qs.stringify(data)
            //         setUserInfo(params)
            //             .then((res) => {
            //                 if (res.data) {
            //                     var data = res.data
            //                     // let mes = JSON.parse(res.data.message)
            //                     if (data.errorID === 0) {
            //                         let userInfo = res.data.object
            //                         this.phone = userInfo.phone || ''
            //                         done();
            //                     } else {
            //                         this.$toast(data.message)
            //                         done();
            //                     }
            //                 }
            //             })
            //             .catch((error) => {
            //                 done();
            //                 this.$toast('error,please try again later')
            //             })
            //
            //     } else {
            //         done();
            //     }
            // },

            //修改邮箱 function

            // setEmailError () {
            //     let reg = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/
            //     if (this.email.match(reg)) {
            //         this.emailError = false
            //     }
            // },
            // setPasswordError () {
            //     let reg = /^(?=.*?).{8,}$/
            //     if (this.password.match(reg)) {
            //         this.passwordError = false
            //     }
            // },
            // getEmail(email) {
            //     if (String(email).indexOf('@') > 0) {
            //         var str = email.split('@'),
            //             _s = '';
            //         if (str[0].length > 2) {
            //             for (var i = 0; i < str[0].length - 2; i++) {
            //                 _s += '*';
            //             }
            //         }
            //         var new_email = str[0].substr(0, 2) + _s + '@' + str[1]
            //     }
            //     return new_email
            // },
            // changeEmail () {
            //     //校验表单开始
            //     // 备用 let reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
            //     let regEmail = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/
            //     let regPassword = /^(?=.*?).{8,}$/
            //     let emailIsCanSubmit = false
            //     let passwordIsCanSubmit = false
            //     if (!this.email.match(regEmail)) {
            //         this.emailError = true
            //     } else {
            //         emailIsCanSubmit = true
            //     }
            //     if (!this.password.match(regPassword)) {
            //         this.passwordError = true
            //     } else {
            //         passwordIsCanSubmit = true
            //     }
            //     if (!emailIsCanSubmit || !passwordIsCanSubmit) return false
            //     //校验表单结束
            //
            //     let data = {
            //         'accountEmail': this.email,
            //         'password': this.password
            //     }
            //     let params = Qs.stringify(data)
            //     this.loadingEmail = true
            //     setUserInfo(params)
            //         .then((res) => {
            //             if (res.data) {
            //                 var data = res.data
            //                 // let mes = JSON.parse(res.data.message)
            //                 if (data.errorID === 0) {
            //                     this.$dialog.alert({
            //                         message: 'Please check your email. if you don\'t receive please check your spam folder',
            //                         confirmButtonText: 'OK'
            //                     })
            //                     this.loadingEmail = false
            //                 } else {
            //                     this.$toast(data.message)
            //                     this.loadingEmail = false
            //                 }
            //             }
            //         })
            //         .catch((error) => {
            //             this.loadingEmail = false
            //             this.$toast('error,please try again later')
            //         })
            // },

            //绑定解绑 Facebook start
            // 調用FaceBook登錄按鈕
            faceBookLogin () {
                window.FB.login((response) =>{
                    this.statusChangeCallback(response)
                },{scope: 'public_profile'});
            },
            statusChangeCallback (response) {
                if (response.status === 'connected') {
                    this.loading = true;
                    FB.api('/me?fields=name,token_for_business',(response) => { // /me为API指定的调用方法，用于获取登陆用户相关信息
                        if(response.id){
                            this.loginBindFaceBook(response)
                        }else{
                            this.$toast('error,please try again later')
                            this.loading = false;
                        }
                    })
                }
            },
            loginBindFaceBook (response) {
                if (response) {
                    var facebookId = response.id
                    let tokenForBusiness = response.token_for_business;
                    var name = response.name
                    // var email = response.email
                    let data = {
                        'facebookId': facebookId,
                        'facebookName': name,
                        // 'facebookEmail': email,
                        'tokenForBusiness': tokenForBusiness,
                    }
                    let params = Qs.stringify(data)

                    this.loading = true;
                    // 调用绑定facebook的接口
                    bindingFacebook(params).then((res) => {
                        let data = res.data
                        if (data.errorID === 0) {
                            this.facebook = name;
                            this.editLocalUserInfo('facebookId', facebookId);
                            this.editLocalUserInfo('facebookName', name);
                            this.editLocalUserInfo('facebookEmail', email);
                            this.loading = false
                        } else {
                            this.$toast(res.data.message);
                            this.loading = false
                        }
                    }).catch((e) => {
                        console.log(e)
                        this.$toast('error,please try again leter');
                        this.loading = false
                    })
                }
            },
            //deleteBindFacebook  解除绑定facebook
            deleteBindFacebook () {
                this.loading = true;
                unBindingFacebook().then((res) => {
                    let data = res.data
                    if (data.errorID === 0) {
                        this.facebook = '';
                        this.editLocalUserInfo('facebookId', '');
                        this.editLocalUserInfo('facebookName', '');
                        this.editLocalUserInfo('facebookEmail', '');
                        this.loading = false
                        // 调用退出Facebook登录方法
                        FB.logout(function (response) {
                            // Person is now logged out
                        });
                    } else {
                        this.$toast(res.data.message)
                        this.loading = false
                    }
                }).catch((e) => {
                    console.log(e);
                    this.$toast('error,please try again leter');
                    this.loading = false
                })
            },
            //绑定解绑 Facebook end
            Logout () {
                signOutUser({}).then((res) => {
                    if (res.data) {
                        var data = res.data
                        if (data.errorID === 0 || data.errorID === 100004) {

                            localStorage.removeItem("userInfo");
                            localStorage.removeItem("userToken");
                            this.$store.commit('store/updateIsLogin', false)
                            // 尝试清除谷歌登录
                            try {
                                var auth2 = window.gapi.auth2.getAuthInstance()
                                auth2.signOut()
                            } catch (e) {

                            }
                            // 尝试清除facebook登录
                            try {
                                FB.logout(function (response) {
                                    // Person is now logged out
                                })
                            } catch (e) {

                            }

                            // 尝试清除聊天系统登录状态
                            try {
                                // console.log('退出聊天登录')
                                localStorage.removeItem("Authorization");
                                localStorage.removeItem("Device-Key");
                                this.$store.commit('store/updateChatLoginStatus', false)
                                window.$applozic.fn.applozic('logout');
                                this.$store.commit('store/updateChatMsgNumber', '')
                            } catch (e) {
                                console.log(e)
                            }

                            this.$router.push('/')
                            location.reload(true)
                        } else {
                            console.log(data.errorID)
                            this.$toast(data.message)
                        }
                    }
                })
                    .catch((error) => {
                        console.log(error)
                        this.$toast('error,please try again leter')
                    })
            },
        },
        watch: {
            screenHeight (val) {
                if(this.originHeight != val) {
                    this.isOriginHei = false;
                }else{
                    this.isOriginHei = true;
                }
            }
        },
        mounted() {
            window.onresize = () => {
                return (() => {
                    window.screenHeight= document.body.clientHeight
                    this.screenHeight= window.screenHeight
                })()
            }
            // if (!window.AccountKit) {
            //     this.initAccountKit()
            // }
            let userInfo = localStorage.getItem("userInfo") || '';
            // 修改description后这里需要优化
            if (userInfo) {
                userInfo = JSON.parse(userInfo)
                this.initInfoData(userInfo)
                this.initInfo()
            } else {
                this.initInfo()
            }
            //初始化裁剪框
            this.initCropper()
        },
        beforeRouteLeave (to, from, next) {
            // 导航离开该组件的对应路由时调用
            // 可以访问组件实例 `this`
            let leave = true;
            if (this.panel) {
                this.panel = false
                leave = false
            }
            if (this.namePop) {
                this.namePop = false
                leave = false
            }
            if (this.genderPop) {
                this.genderPop = false
                leave = false
            }
            if (this.birthDatePop) {
                this.birthDatePop = false
                leave = false
            }
            if (this.propertyShow) {
                this.propertyShow = false
                this.filterShow = true
                leave = false
            }
            if (leave) {
                next()
            } else {
                next(false)
            }
        }
    };
</script>
<style>
    .description-cell .van-cell__value{
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .page-profile .van-nav-bar{
        background-color: #FF9900;
    }
    .page-profile .van-nav-bar .van-icon{
        color: #fff;
        margin-right: 15px;
        font-size: 18px;
    }
    .head-image.van-cell{
        line-height: 60px;
    }
    .head-image .van-cell__right-icon{
        line-height: 60px;
    }
    .facebook-bind .van-cell__value{
        color:#FFA603;
    }

    .cropper-view-box,.cropper-face {
        border-radius: 50%;
    }
    /*!
     * Cropper.js v1.0.0-rc
     * https://github.com/fengyuanchen/cropperjs
     *
     * Copyright (c) 2017 Fengyuan Chen
     * Released under the MIT license
     *
     * Date: 2017-03-25T12:02:21.062Z
     */

    .cropper-container {
        font-size: 0;
        line-height: 0;

        position: relative;

        -webkit-user-select: none;

        -moz-user-select: none;

        -ms-user-select: none;

        user-select: none;

        direction: ltr;
        -ms-touch-action: none;
        touch-action: none
    }

    .cropper-container img {
        /* Avoid margin top issue (Occur only when margin-top <= -height) */
        display: block;
        min-width: 0 !important;
        max-width: none !important;
        min-height: 0 !important;
        max-height: none !important;
        width: 100%;
        height: 100%;
        image-orientation: 0deg
    }

    .cropper-wrap-box,
    .cropper-canvas,
    .cropper-drag-box,
    .cropper-crop-box,
    .cropper-modal {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }

    .cropper-wrap-box {
        overflow: hidden;
    }

    .cropper-drag-box {
        opacity: 0;
        background-color: #fff;
    }

    .cropper-modal {
        opacity: .5;
        background-color: #000;
    }

    .cropper-view-box {
        display: block;
        overflow: hidden;

        width: 100%;
        height: 100%;

        outline: 1px solid #39f;
        outline-color: rgba(51, 153, 255, 0.75);
    }

    .cropper-dashed {
        position: absolute;

        display: block;

        opacity: .5;
        border: 0 dashed #eee
    }

    .cropper-dashed.dashed-h {
        top: 33.33333%;
        left: 0;
        width: 100%;
        height: 33.33333%;
        border-top-width: 1px;
        border-bottom-width: 1px
    }

    .cropper-dashed.dashed-v {
        top: 0;
        left: 33.33333%;
        width: 33.33333%;
        height: 100%;
        border-right-width: 1px;
        border-left-width: 1px
    }

    .cropper-center {
        position: absolute;
        top: 50%;
        left: 50%;

        display: block;

        width: 0;
        height: 0;

        opacity: .75
    }

    .cropper-center:before,
    .cropper-center:after {
        position: absolute;
        display: block;
        content: ' ';
        background-color: #eee
    }

    .cropper-center:before {
        top: 0;
        left: -3px;
        width: 7px;
        height: 1px
    }

    .cropper-center:after {
        top: -3px;
        left: 0;
        width: 1px;
        height: 7px
    }

    .cropper-face,
    .cropper-line,
    .cropper-point {
        position: absolute;

        display: block;

        width: 100%;
        height: 100%;

        opacity: .1;
    }

    .cropper-face {
        top: 0;
        left: 0;

        background-color: #fff;
    }

    .cropper-line {
        background-color: #39f
    }

    .cropper-line.line-e {
        top: 0;
        right: -3px;
        width: 5px;
        cursor: e-resize
    }

    .cropper-line.line-n {
        top: -3px;
        left: 0;
        height: 5px;
        cursor: n-resize
    }

    .cropper-line.line-w {
        top: 0;
        left: -3px;
        width: 5px;
        cursor: w-resize
    }

    .cropper-line.line-s {
        bottom: -3px;
        left: 0;
        height: 5px;
        cursor: s-resize
    }

    .cropper-point {
        width: 5px;
        height: 5px;

        opacity: .75;
        background-color: #39f
    }

    .cropper-point.point-e {
        top: 50%;
        right: -3px;
        margin-top: -3px;
        cursor: e-resize
    }

    .cropper-point.point-n {
        top: -3px;
        left: 50%;
        margin-left: -3px;
        cursor: n-resize
    }

    .cropper-point.point-w {
        top: 50%;
        left: -3px;
        margin-top: -3px;
        cursor: w-resize
    }

    .cropper-point.point-s {
        bottom: -3px;
        left: 50%;
        margin-left: -3px;
        cursor: s-resize
    }

    .cropper-point.point-ne {
        top: -3px;
        right: -3px;
        cursor: ne-resize
    }

    .cropper-point.point-nw {
        top: -3px;
        left: -3px;
        cursor: nw-resize
    }

    .cropper-point.point-sw {
        bottom: -3px;
        left: -3px;
        cursor: sw-resize
    }

    .cropper-point.point-se {
        right: -3px;
        bottom: -3px;
        width: 20px;
        height: 20px;
        cursor: se-resize;
        opacity: 1
    }

    @media (min-width: 768px) {

        .cropper-point.point-se {
            width: 15px;
            height: 15px
        }
    }

    @media (min-width: 992px) {

        .cropper-point.point-se {
            width: 10px;
            height: 10px
        }
    }

    @media (min-width: 1200px) {

        .cropper-point.point-se {
            width: 5px;
            height: 5px;
            opacity: .75
        }
    }

    .cropper-point.point-se:before {
        position: absolute;
        right: -50%;
        bottom: -50%;
        display: block;
        width: 200%;
        height: 200%;
        content: ' ';
        opacity: 0;
        background-color: #39f
    }

    .cropper-invisible {
        opacity: 0;
    }

    .cropper-bg {
        background-image: url('');
    }

    .cropper-hide {
        position: absolute;

        display: block;

        width: 0;
        height: 0;
    }

    .cropper-hidden {
        display: none !important;
    }

    .cropper-move {
        cursor: move;
    }

    .cropper-crop {
        cursor: crosshair;
    }

    .cropper-disabled .cropper-drag-box,
    .cropper-disabled .cropper-face,
    .cropper-disabled .cropper-line,
    .cropper-disabled .cropper-point {
        cursor: not-allowed;
    }
    .page-profile .van-loading{
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -15px;
        margin-left: -15px;
    }

</style>
<style scoped>
    .phone-box{
        padding-left: 40px;
    }
    #demo #button {
        position: absolute;
        right: 10px;
        top: 10px;
        width: 80px;
        height: 40px;
        border:none;
        border-radius: 5px;
        background:white;
    }
    #demo #cancel {
        position: absolute;
        left: 10px;
        top: 10px;
        width: 80px;
        height: 40px;
        border:none;
        border-radius: 5px;
        background:white;
    }
    #demo .show {
        width: 100px;
        height: 100px;
        overflow: hidden;
        position: relative;
        border-radius: 50%;
        border: 1px solid #d5d5d5;
    }
    #demo .picture {
        width: 100%;
        height: 100%;
        overflow: hidden;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
    }
    #demo .container {
        z-index: 99;
        position: fixed;
        padding-top: 60px;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        background:rgba(0,0,0,1);
    }

    #demo #image {
        max-width: 100%;
    }
.profile{
     height:100%;
    display: flex;
    display:-ms-flex;
    display:-webkit-flex;
    flex-direction: column;
    position: relative;
}
.profile .loading{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 999;
    background: rgba(255,255,255,.5);
}
.profile .loading .loading-inside{
    position: relative;
    width: 100%;
    height: 100%;
}
.head-image{
    height: 80px;
    /*line-height: 60px;*/
}
.head-image .image-icon{
    height: 60px;
    width: 60px;
    border-radius: 50%;
}
.login-box-inside {
    padding: 12px 16px;
}
.login-box-inside .login-btn{
    height: 42px;
    margin-top: 24px;
}
.label-class{
    text-align: left;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #5a5e66;
    line-height: 32px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
}
.label-class:after {
    content: "*";
    color: #fa5555;
    margin-left: 4px;
}
.input-class {
    -webkit-appearance: none;
    background-color: #fff;
    border: 1px solid #d8dce5;
    box-sizing: border-box;
    color: #5a5e66;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 1;
    outline: 0;
    padding: 0 15px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    width: 100%;
}
.input-class.text-danger{
    border: 1px solid #fa5555;
}
.email-login-box{
    padding: 20px 15px;
    box-sizing: border-box;
}
.login-loading {
    display: inline-block;
    margin-right: 8px;
    margin-left: -10px;
}
.login-btn {
    height: 42px;
    margin-top: 20px;
}
.login-btn .btn{
    background-color: rgb(255, 153, 0);
    border: 0;
    color: #fff;
    border-radius: 0px;
    width: 100%;
    height: 100%;
    line-height: 1;
}
.login-btn .van-button--disabled.btn{
    color: #999;
}
.email-box-title{
    text-align: center;
}
.filter-btn {
    /*position: fixed;*/
    /*left: 0;*/
    /*right: 0;*/
    margin: 0 auto;
    /*bottom: 20px;*/
    margin-bottom: 20px;
    /*display: flex;*/
    padding: 0 4%;
    font-size: 14px;
    text-align: center;
    width: 92%;
    position: relative;
}
.filter-btn .logout-btn{
    border:1px solid #666666;
    border-radius: 5px;
    height: 45px;
    line-height: 43px;
    color: #FF0000;
    display: block;
}
.user-info-box{
    flex:1;-ms-flex:1;-webkit-flex:1
}
.email-box p {
    margin-bottom: 0;
}

</style>
